package org.android.brasil.projetos.oktoberfest2011.negocio.servico;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.List;

import org.android.brasil.projetos.oktoberfest2011.negocio.model.Tweet;
import org.android.brasil.projetos.oktoberfest2011.negocio.model.TwitterResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.google.gson.Gson;

public class TwitterHelper {

	private static final String SEARCH_URL = "http://search.twitter.com/search.json?q=%s&rpp=%d&page=%d";

	public static List<Tweet> retrieveTweets(String searchTerm, int responsePerPage, int page) {
		searchTerm = searchTerm.replaceAll("[#]", "%23");
		searchTerm = searchTerm.replaceAll("[@]", "%40");
		searchTerm = searchTerm.replaceAll("[ ]", "%20");
		String searchUrl = String.format(SEARCH_URL, searchTerm, responsePerPage, page);
		Gson gson = new Gson();

		InputStream source = TwitterHelper.retrieveStream(searchUrl);
		Reader reader = new InputStreamReader(source);
		TwitterResponse response = gson.fromJson(reader, TwitterResponse.class);
		return response.results;
	}

	private static InputStream retrieveStream(String url) {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet getRequest = new HttpGet(url);
		try {
			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w(TwitterHelper.class.getName(),
						String.format("Error %d for URL %s", statusCode, url));
				return null;
			}

			HttpEntity getResponseEntity = getResponse.getEntity();
			return getResponseEntity.getContent();

		} catch (IOException e) {
			getRequest.abort();
			Log.w(TwitterHelper.class.getName(),
					String.format("Error for URL %s", url), e);
		}

		return null;

	}

	public static Bitmap getAvatar(String bitmapUrl) {
		try {
			URL url = new URL(bitmapUrl);
			return BitmapFactory.decodeStream(url.openConnection().getInputStream());
		} catch (Exception ex) {
			return null;
		}
	}

}
